<?php
/*
 * Ruffy.php - Main file for the Ruffy IRC Bot
 * Written by Nick Markwell
 *
 * Part of the Ruffy IRC Bot
 * http://rockermono.nonlogic.org/projects/
 *
 * Ruffy is slightly based on the connection portions of the Xando/BONO IRC Bots
 *
 */

//error_reporting(E_ERROR | E_WARNING | E_PARSE); // This will NOT report uninitialized variables ,etc

$debug = false;
include("ruffy.config.php");

$floodIgnores=Array();

$startTime=microtime(true);

$version=7.0;
$verStr=(string)$version;
if(!stristr($verStr,".")){
  $version=number_format($version,1);
  $verStr=(string)$version;
}
$useColors=true;
$commandSent=false;
$allCommands=Array();
$antiFloodGlobal=0;
$antiFloodGlobalTime=time();
$antiFlood=Array();
$antiFloodTime=Array();

include("functions.php");
include("controls/memory.php");
include("controls/common.php");

if(!empty($_SERVER['argv'][1])){
	$network=$_SERVER['argv'][1];
	if(stristr($network,":")){
	  $networkA=explode(":",$network);
	  $network=$networkA[sizeOf($networkA)-2];
	  $port=$networkA[sizeOf($networkA)-1];
	}
//} else {
//  $network="zeus.devnode.org";
}

file_put_contents("data/ruffy-$network.pid", getmypid());

// The Access levels Array, probably wise to not edit it directly
if(file_exists("data/access.dat")){
  $levels=unserialize(file_get_contents("data/access.dat"));
}

if(!empty($_SERVER['argv'][2])){
	if(stristr($_SERVER['argv'][2],";")){
	  $channels=explode(';',$_SERVER['argv'][2]);
	} else {
	  $channels=Array($_SERVER['argv'][2]);
	}
} else {
  $channels=$defaultChannels;
}

if(!empty($_SERVER['argv'][3])){
  if(!empty($prefix)){
    $prefix=$_SERVER['argv'][3];
  }
}
$allCommands="";
$originalNick=$nickname;
$checkWhois=false;
$ghosted=false;

while(true)
{
	if(!empty($nickname)){
		$server_host = $network;
		if(empty($port)){
			$server_port=6667;
		} else {
			$server_port=$port;
		}

		$joined=false;

    //$server = array();
    echo ">!< Connecting to $server_host:$server_port...\r\n";
    $socket = @fsockopen($server_host, $server_port, $errno, $errstr, 2);
    if(!$socket)
    {
    	echo ">!< Unable to connect to $server_host:$server_port.\r\n";
    }
    else
    {
    	echo ">!< Connected to $server_host:$server_port.\r\n";
      send("NICK $nickname");
      send("USER $nickname * * :Ruffy v$version by duck, heavily edited by danopia");
      while(!@feof($socket) && $socket != -1)
      {
        $data = @fgets($socket, 1024); //get a line of data from the server
		    $data = str_replace(array("\n", "\r"), '', $data);           
    		$data = str_replace(chr(7), '*', $data);
				echo "<<< $data\r\n";
				
				if ($data == '')
					send('PING :TIMEOUTCHECK');
				
				include('parser.php'); // Danopia's parsing engine.
				
				if(array_key_exists($source_host,$levels))
					$level = $levels[$source_host];
				else
					$level = 0;
        
        if($command == '1')
				{
					send("MODE $nickname +B");
          send("PRIVMSG Nickserv :identify ".$password[strtolower($network)],true);
          send("JOIN ".implode(",",$channels));
					$joined=true;
        }

        if($command == '433'){
          $nickname .= '`';
          send("NICK $nickname");
        }

        if($joined){
        	
        	// Handle the modules variables
					$modules = array();
					$current_module = '';

					foreach(dirlist("./modules/",true) as $module){
						if(substr($module,strlen($module)-4)==".php" and substr($module,strlen("./modules/"),1)!="_"){
							$moduleText=file_get_contents($module);
							$moduleText=substr($moduleText,5,strlen($moduleText)-7);
							
        			// Handle the modules variables
        			$temp = explode('/', $module);
							$current_module = substr($temp[2], 0, strlen($temp[2])-4);
							if ($debug) echo $currentmodule;
							$modules[$current_module] = array();
							
							if ($debug) echo $current_module . ' '; // So you know which module is failing
							
							try{
								eval($moduleText);
							} catch(Exception $e){
								if ($debug) echo "\r\n\r\n" . $e->getMessage() . "\r\n\r\n";
								echo "\r\nError in $module\r\n";
							}
							//include($module);
						}
					}
					
					if ($debug) echo "\r\n"; // Complements the above debug line
					
					if(($msg_cmd == 'help') || ($msg_cmd == 'list')){
						if (count($msg_args) == 1) {
							$return = array();
							foreach($modules as $module => $commands){
								if (count($commands) > 0)
									$return[] = $module . '(' . count($commands) . ')';
							}
							notice('Current modules: ' . implode(', ', $return) . '. To list the commands in a module, use the help <module> command. The number in parathesis is the number of commands in the module.', $source_nick);
						} else {
							if (array_key_exists($msg_args[1], $modules)) {
								$return = array();
								foreach($modules[$msg_args[1]] as $command => $cmd_level){
									$return[] = "$command($cmd_level)";
								}
								if (count($return) == 0)
									notice("Module $msg_args[1] does not comtain any standard commands.", $source_nick);
								else
									notice("Commands in module $msg_args[1]: " . implode(', ', $return) . '. The number in parathesis in the minimum required level for the command.', $source_nick);
							} else {
								notice("Sorry, the $msg_args[1] module does not exist.", $source_nick);
							}
						}
					}
				}

        $uFloodTime=time();
        $uFloodTime-=10;
        if(!is_array($antiFlood)){
          $antiFlood=Array();
        }
        if(!is_array($antiFloodTime)){
          $antiFloodTime=Array();
        }
        if(!array_key_exists($source_nick,$antiFloodTime)){
          $antiFloodTime[$source_nick]=time();
        }
        if(!array_key_exists($source_nick,$antiFlood)){
          $antiFlood[$source_nick]=0;
        }
        if($antiFloodTime[$source_nick]<=$uFloodTime){
          if($antiFlood[$source_nick]>0){
            $antiFlood[$source_nick]--;
          } else {
            $antiFloodTime[$source_nick]=time();
          }
        }
        if($antiFloodGlobalTime<=$uFloodTime){
          if($antiFloodGlobal>0){
            $antiFloodGlobal--;
          }
        }

        if($command == 'PING')
          send("PONG :$message");
        
		// This is for when Ruffy is run in your Web Browser.
        flush();
     }
  }
}

echo ">!< Connection lost. Reconnecting in 10 seconds.\r\n";
// no instant reconnects! wait 10 seconds so it wont freeze your computer or get klined 
sleep(10);
}
?>
